package model

import (
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"time"
)

type User struct {
	ID        uint      `gorm:"primaryKey;autoIncrement" json:"id"`
	Phone     string    `gorm:"type:varchar(20);uniqueIndex;not null" json:"phone"`
	Password  string    `gorm:"type:varchar(255);not null" json:"-"`
	CreatedAt time.Time `json:"created_at,omitempty"`
	UpdatedAt time.Time `json:"updated_at,omitempty"`
}

// HashPassword 对密码进行 bcrypt 加密
func HashPassword(password string) string {
	bytes, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(bytes)
}

// VerifyPassword 验证密码
func (u *User) VerifyPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	return err == nil
}

// Create 创建用户
func (u *User) Create(db *gorm.DB) error {
	return db.Create(u).Error
}

// GetByPhone 根据手机号查询用户
func (u *User) GetByPhone(db *gorm.DB, phone string) error {
	return db.Where("phone = ?", phone).First(u).Error
}

// IsPhoneExists 判断手机号是否已存在
func IsPhoneExists(db *gorm.DB, phone string) bool {
	var count int64
	db.Model(&User{}).Where("phone = ?", phone).Count(&count)
	return count > 0
}
